var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var user = require('../../../services/user.js');
var app = getApp();
Component({
  options: {
    addGlobalClass: true,
  },
  data: {},
  //组件生命周期函数-在组件实例进入页面节点树时执行)
  attached() {

    let userInfo = wx.getStorageSync('userInfo');
    let token = wx.getStorageSync('token');
    // 页面显示
    if (userInfo) {
      app.globalData.userInfo = userInfo;
      this.setData({
        userInfo: app.globalData.userInfo,
      });
    }

    if (token) {
      app.globalData.token = token;
    }
  },
  //组件的方法，包括事件响应函数和任意的自定义方法，关于事件响应函数的使用
  methods: {
    bindGetUserInfo(e) {
      let userInfo = wx.getStorageSync('userInfo');
      let token = wx.getStorageSync('token');
      if (userInfo && token) {
        return;
      }
      let that = this;
      if (e.detail.userInfo) {
        //用户按了允许授权按钮
        user.loginByWeixin(e.detail).then(res => {
          that.setData({
            userInfo: res.result.userInfo
          });
          app.globalData.userInfo = res.result.userInfo;
          app.globalData.token = res.result.token;
        }).catch((err) => {
          //登入失败 再次尝试
          user.loginByWeixin(e.detail).then(res => {
            that.setData({
              userInfo: res.result.userInfo
            });
            app.globalData.userInfo = res.result.userInfo;
            app.globalData.token = res.result.token;
          }).catch((err) => {
            console.log(err)
          });
        });
      } else {
        //用户按了拒绝按钮
        wx.showModal({
          title: '警告通知',
          content: '您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。',
          success: function(res) {
            if (res.confirm) {
              wx.openSetting({
                success: (res) => {
                  if (res.authSetting["scope.userInfo"]) { ////如果用户重新同意了授权登录
                    user.loginByWeixin(e.detail).then(res => {
                      that.setData({
                        userInfo: res.result.userInfo
                      });
                      app.globalData.userInfo = res.result.userInfo;
                      app.globalData.token = res.result.token;
                    }).catch((err) => {
                      //登入失败 再次尝试
                      user.loginByWeixin(e.detail).then(res => {
                        that.setData({
                          userInfo: res.result.userInfo
                        });
                        app.globalData.userInfo = res.result.userInfo;
                        app.globalData.token = res.result.token;
                      }).catch((err) => {
                        console.log(err)
                      });
                    });
                  }
                }
              })
            }
          }
        });
      }
    },
    nav(e){
      wx.navigateTo({
        url: e.currentTarget.dataset.page,
      })
    }
  }
})